package xyz.myachin.downloader.ui.share

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import xyz.myachin.downloader.*
import xyz.myachin.downloader.dm.Downloader
import xyz.myachin.downloader.workmanagers.RemoveDownloadsWorker

class SharingActivity : Activity() {
    private val mDm = Downloader

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (intent?.action == null) {
            finish()
            return
        }
        handleIntent(intent)
    }

    private fun handleIntent(intent: Intent) {
        when (intent.action) {
            ACTION_DOWNLOAD_FILE -> {
                intent.getStringExtra(EXTRA_ADD_DOWNLOAD_TASK)?.let { url ->
                    Thread {
                        var sharingType = SharingType.MANUAL
                        if (intent.getBooleanExtra(EXTRA_DIRECT, false)) {
                            sharingType = SharingType.DIRECT
                        }
                        mDm.enqueue(mDm.prepareDownloadTask(Uri.parse(url)), sharingType)
                        finish()
                    }.start()
                }
            }

            ACTION_REMOVE_ALL -> {
                RemoveDownloadsWorker.cleanAll(force = true)
                Toast.makeText(applicationContext, R.string.done, Toast.LENGTH_SHORT).show()
                finish()
            }

            ACTION_REMOVE_FILE -> {
                Thread {
                    val taskId = intent.getLongExtra(FILE_ID, -1)
                    revokeUriPermission(
                        mDm.getLocalUriForDownloadedFile(taskId),
                        Intent.FLAG_GRANT_READ_URI_PERMISSION
                    )
                    mDm.removeTasks(taskId)
                    finish()
                }.start()
            }
            else -> finish()
        }
    }
}